package com.gs.m_home

import android.animation.ValueAnimator
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationListener
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.gs.common.BaseCompatActivity
import com.gs.common.global.GlobalVariables
import com.gs.common.manager.ActivityManager
import com.gs.common.util.ActionBarUtil
import com.gs.common.util.LocationUtil
import com.gs.common.util.StringUtil
import com.gs.common.util.ToastUtil
import com.gs.m_home.databinding.HomeLayoutBinding
import com.gs.common.observal.ValueObserval
import com.gs.common.observer.ValueObserver
import pub.devrel.easypermissions.EasyPermissions


class HomeActivity : BaseCompatActivity(), AMapLocationListener, EasyPermissions.PermissionCallbacks {

    private lateinit var binding: HomeLayoutBinding
    private lateinit var mActionBarTitle: TextView
    private lateinit var mSearchLayout: RelativeLayout
    private lateinit var mSearchExitBtn: ImageView
    private lateinit var mSearchEdit: EditText
    private lateinit var mSearchButtonActive: ImageView
    private lateinit var mSearchButtonInactive: ImageView
    private lateinit var mCartDeleteButton: ImageView
    private lateinit var mCartExitDeleteButton: ImageView
    private lateinit var mParamValueObserval: ValueObserval<Int> // 搜索框的宽度被关注对象
    private lateinit var mLocationClient: AMapLocationClient
    private lateinit var mLocationUtil: LocationUtil

    private val mFragmentLifecycleCallbacks =
        object : FragmentManager.FragmentLifecycleCallbacks() {
            private lateinit var actionBarTitle: TextView
            private lateinit var location: LinearLayout
            private lateinit var searchButton: ImageView
            private lateinit var searchRelativeLayout: RelativeLayout
            override fun onFragmentResumed(fm: FragmentManager, f: Fragment) {
                super.onFragmentResumed(fm, f)

            }

            override fun onFragmentStarted(fm: FragmentManager, f: Fragment) {
                super.onFragmentStarted(fm, f)
                actionBarTitle = findViewById(R.id.action_bar_title)
                location = findViewById<LinearLayout>(R.id.location)
                searchButton = findViewById<ImageView>(R.id.search_button_inactive)
                searchRelativeLayout = findViewById<RelativeLayout>(R.id.search_layout)
                val deleteButton = findViewById<ImageView>(R.id.delete_button)
                val exitDeleteButton = findViewById<ImageView>(R.id.exit_delete_button)
                when {
                    f.toString().contains("ShoppingFragment") -> {
                        actionBarTitle.visibility = View.VISIBLE
                        actionBarTitle.text = "首页"
                        location.visibility = View.VISIBLE
                        searchButton.visibility = View.VISIBLE
                        deleteButton.visibility = View.GONE
                        exitDeleteButton.visibility = View.GONE
                    }

                    f.toString().contains("CartFragment") -> {
                        actionBarTitle.visibility = View.VISIBLE
                        actionBarTitle.text = "购物车"
                        location.visibility = View.INVISIBLE
                        searchButton.visibility = View.INVISIBLE
                        searchRelativeLayout.visibility = View.GONE
                        deleteButton.visibility = View.VISIBLE
                        exitDeleteButton.visibility = View.GONE
                    }

                    f.toString().contains("MineFragment") -> {
                        actionBarTitle.visibility = View.VISIBLE
                        actionBarTitle.text = "我的"
                        location.visibility = View.INVISIBLE
                        searchButton.visibility = View.INVISIBLE
                        searchRelativeLayout.visibility = View.GONE
                        deleteButton.visibility = View.GONE
                        exitDeleteButton.visibility = View.GONE
                    }
                }
            }

            override fun onFragmentDestroyed(fm: FragmentManager, f: Fragment) {
                super.onFragmentDestroyed(fm, f)
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = HomeLayoutBinding.inflate(layoutInflater)
        setContentView(binding.root)

        mParamValueObserval = ValueObserval()

        supportFragmentManager.registerFragmentLifecycleCallbacks(mFragmentLifecycleCallbacks, true)

        // 设置自定义 action bar
        ActionBarUtil.setCustomActionBar(this, R.layout.actionbar_layout)

        //配置bottom navigation
        val navView: BottomNavigationView = binding.navView

        val navController = findNavController(R.id.nav_host_fragment_activity_home)
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
//        val appBarConfiguration = AppBarConfiguration(
//            setOf(
//                R.id.navigation_shopping, R.id.navigation_cart, R.id.navigation_mine
//            )
//        )
//        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)

        // 加载定位工具
        mLocationUtil = LocationUtil()
        // 初始化定位
        mLocationClient = mLocationUtil.initLocation(this, this)
        // 启动定位
        mLocationUtil.startLocation(this)

        val currentAddress = findViewById<TextView>(R.id.current_address)
        currentAddress.addTextChangedListener {
            if (currentAddress.text.equals("暂无定位")) {
                for (i in 1..10) {
                    mLocationUtil.startLocation(this)
                    if (!currentAddress.text.equals("暂无定位")) {
                        break
                    }
                }
            }
        }

        // 初始化搜索视图
        initView()
    }

    override fun onResume() {
        super.onResume()

        // 销毁之前的所有activity
        ActivityManager.finishAllActivityExceptHomeActivity()

        mActionBarTitle = findViewById(R.id.action_bar_title)

        // 激活搜索框
        mSearchButtonInactive.setOnClickListener {
            activeSearchButton()
        }
        // 退出搜索框
        mSearchExitBtn.setOnClickListener {
            inactiveSearchButton()
        }

        mSearchEdit.setOnEditorActionListener { v, actionId, event ->
                if (event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER) {
                    val searchContent = mSearchEdit.text.toString()
                    doShoppingFragmentShowGoods(searchContent)
                }
                return@setOnEditorActionListener true
        }

        mSearchButtonActive.setOnClickListener {
            doShoppingFragmentShowGoods(mSearchEdit.text.toString())
        }

        mCartDeleteButton.setOnClickListener {
            GlobalVariables.deleteSingle.notifyObserver(true)
            mCartDeleteButton.visibility = View.GONE
            mCartExitDeleteButton.visibility = View.VISIBLE
        }

        mCartExitDeleteButton.setOnClickListener {
            GlobalVariables.deleteSingle.notifyObserver(false)
            mCartExitDeleteButton.visibility = View.GONE
            mCartDeleteButton.visibility = View.VISIBLE
        }

    }
    private fun doShoppingFragmentShowGoods(searchContent: String) {
        GlobalVariables.dataListener?.onDataReceived(searchContent)
        // 隐藏键盘
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(mSearchEdit.windowToken, 0)
    }

    override fun onDestroy() {
        super.onDestroy()
        GlobalVariables.dataListener = null
        mLocationClient.stopLocation()
        mLocationClient.onDestroy()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true) // 将当前app状态直接保存到后台，再次点击时还是当前界面
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun activeSearchButton() {
        mSearchButtonInactive.visibility = View.INVISIBLE
        mSearchLayout.visibility = View.VISIBLE
        doSearchAnimation("active")
        mParamValueObserval.addObserver(object : ValueObserver<Int> {
            override fun update(condition: String, value: Int) {
                if (condition == "active" && value >= 230) {
                    mActionBarTitle.visibility = View.INVISIBLE
                }
            }
        })
    }

    private fun inactiveSearchButton() {
        doSearchAnimation("inactive")
        mActionBarTitle.visibility = View.VISIBLE
        mParamValueObserval.addObserver(object : ValueObserver<Int> {
            override fun update(condition: String, value: Int) {
                if (condition == "inactive" && value <= 50) {
                    mSearchButtonInactive.visibility = View.VISIBLE
                }
            }
        })
    }

    private fun doSearchAnimation(mode: String) {
        val valueAnimator = ValueAnimator.ofInt(0, 230)
        valueAnimator.setDuration(700)
        valueAnimator.addUpdateListener {
            val value = it.animatedValue as Int
            val searchLayout = findViewById<RelativeLayout>(R.id.search_layout)
            val params = searchLayout.layoutParams
            params.width = if (mode == "active") {
                 dpToPx(value)
            } else {
                dpToPx(230) - dpToPx(value)
            }
            mParamValueObserval.notifyObserver(mode, params.width)
            params.height = params.height
            searchLayout.layoutParams = params
        }
        valueAnimator.start()
    }

    private fun initView() {
        mSearchLayout = findViewById(R.id.search_layout)
        mSearchExitBtn = findViewById(R.id.search_exit_btn)
        mSearchEdit = findViewById(R.id.search_edit)
        mSearchButtonActive = findViewById(R.id.search_button_active)
        mSearchButtonInactive = findViewById(R.id.search_button_inactive)
        mCartDeleteButton = findViewById(R.id.delete_button)
        mCartExitDeleteButton = findViewById(R.id.exit_delete_button)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        // 设置权限请求结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onPermissionsGranted(p0: Int, p1: MutableList<String>) {
        mLocationClient.startLocation()
    }

    override fun onPermissionsDenied(p0: Int, p1: MutableList<String>) {
        ToastUtil.showShortToast(this, "权限开启失败！")
    }

    override fun onLocationChanged(p0: AMapLocation?) {
        if (p0 != null) {
            if (p0.errorCode == 0) {
                // 地址
                val address = p0.district + p0.street + p0.description
                val abbrAddress = if (address.length > 3) {
                    address.subSequence(0, 3).toString() + "..."
                } else {
                    address
                }
                val currentAddress = findViewById<TextView>(R.id.current_address)
                if (address.length > 3)
                    currentAddress.text = StringUtil.replaceEmptyString(abbrAddress, "暂无定位")
                currentAddress.tooltipText = StringUtil.replaceEmptyString(address, "暂无定位")
                mLocationClient.stopLocation()
            } else {
                Log.e(
                    "AmapError", "location Error, ErrCode:"
                            + p0.errorCode + ", errInfo:"
                            + p0.errorInfo
                )
            }
        }
    }

    fun restartLocation(view: View) {
        ToastUtil.showShortToast(this, "重新定位")
        mLocationUtil.startLocation(this)
    }



}